import http from '@/utils/axios'
import type { 
  ProductionPlanQueryDto, 
  ProductionPlanPageResult, 
  ProductionPlanApiResult 
} from '@/types/productionPlan'
import type { 
  CreateProductionPlanDto,
  ItemQueryDto, 
  ItemPageResult,
  SalesOrderQueryDto, 
  SalesOrderPageResult,
  SalesOrderItemQueryDto, 
  SalesOrderItemPageResult
} from '@/types/productionPlan'
import type { Project } from '@/types/project'
import type { ProductionPlanDetail } from '@/types/productionPlan'
import { ElMessage } from 'element-plus'

// 分页查询生产计划
export const getProductionPlanPage = async (query: ProductionPlanQueryDto): Promise<ProductionPlanApiResult<ProductionPlanPageResult>> => {
  try {
    const response = await http.post('/ProductionPlan/page', query)
    return response.data
  } catch (error: any) {
    console.error('获取生产计划分页数据失败:', error)
    
    // 返回友好的错误信息
    if (error.response?.status === 404) {
      return {
        msg: 'API接口不存在，请检查接口地址',
        code: 404,
        data: {
          totalCount: 0,
          totalPages: 0,
          pageIndex: 0,
          pageSize: 0,
          items: []
        }
      }
    } else if (error.response?.status === 500) {
      return {
        msg: '服务器内部错误，请稍后重试',
        code: 500,
        data: {
          totalCount: 0,
          totalPages: 0,
          pageIndex: 0,
          pageSize: 0,
          items: []
        }
      }
    } else if (error.code === 'ECONNABORTED') {
      return {
        msg: '请求超时，请检查网络连接',
        code: 408,
        data: {
          totalCount: 0,
          totalPages: 0,
          pageIndex: 0,
          pageSize: 0,
          items: []
        }
      }
    }
    
    return {
      msg: '获取生产计划数据失败，请重试',
      code: 500,
      data: {
        totalCount: 0,
        totalPages: 0,
        pageIndex: 0,
        pageSize: 0,
        items: []
      }
    }
  }
}

// 导出生产计划
export const exportProductionPlan = async (query: ProductionPlanQueryDto): Promise<Blob> => {
  try {
    const response = await http.post('/ProductionPlan/export', query, {
      responseType: 'blob',
      timeout: 30000 // 导出可能需要更长时间
    })
    
    // 检查响应类型
    const contentType = response.headers['content-type']
    if (contentType && contentType.includes('application/json')) {
      // 如果返回的是JSON错误信息，需要解析
      const reader = new FileReader()
      const text = await new Promise<string>((resolve) => {
        reader.onload = () => resolve(reader.result as string)
        reader.readAsText(response.data)
      })
      
      try {
        const errorData = JSON.parse(text)
        throw new Error(errorData.msg || '导出失败')
      } catch {
        throw new Error('导出失败，请重试')
      }
    }
    
    return response.data
  } catch (error: any) {
    console.error('导出生产计划失败:', error)
    
    if (error.response?.status === 404) {
      throw new Error('导出接口不存在，请检查接口地址')
    } else if (error.response?.status === 500) {
      throw new Error('服务器内部错误，请稍后重试')
    } else if (error.code === 'ECONNABORTED') {
      throw new Error('导出超时，请检查网络连接')
    }
    
    throw new Error(error.message || '导出失败，请重试')
  }
}

// 删除生产计划
export const deleteProductionPlan = async (id: number): Promise<ProductionPlanApiResult<boolean>> => {
  try {
    const response = await http.delete(`/ProductionPlan/${id}`)
    return response.data
  } catch (error: any) {
    console.error('删除生产计划失败:', error)
    
    if (error.response?.status === 404) {
      return {
        msg: '要删除的生产计划不存在',
        code: 404,
        data: false
      }
    } else if (error.response?.status === 403) {
      return {
        msg: '没有权限删除此生产计划',
        code: 403,
        data: false
      }
    } else if (error.response?.status === 500) {
      return {
        msg: '服务器内部错误，请稍后重试',
        code: 500,
        data: false
      }
    }
    
    return {
      msg: '删除失败，请重试',
      code: 500,
      data: false
    }
  }
}

// 生产计划详情相关API
export const getProductionPlanDetail = async (id: number): Promise<ProductionPlanDetail> => {
  try {
    const response = await http.get(`/ProductionPlan/${id}`)
    return response.data.data
  } catch (error: any) {
    console.error('获取生产计划详情失败:', error)
    throw new Error(error.response?.data?.msg || '获取生产计划详情失败')
  }
}

export const exportProductionPlanItems = async (id: number): Promise<void> => {
  try {
    const response = await http.get(`/ProductionPlan/${id}/export-items`, {
      responseType: 'blob'
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `生产计划${id}物品清单.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('生产物品导出成功')
  } catch (error: any) {
    console.error('导出生产物品失败:', error)
    ElMessage.error('导出生产物品失败')
  }
}

export const exportProductionPlanLogs = async (id: number): Promise<void> => {
  try {
    const response = await http.get(`/ProductionPlan/${id}/export-logs`, {
      responseType: 'blob'
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `生产计划${id}操作记录.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('操作记录导出成功')
  } catch (error: any) {
    console.error('导出操作记录失败:', error)
    ElMessage.error('导出操作记录失败')
  }
}

// 创建生产计划（为后续功能预留）
export const createProductionPlan = async (data: CreateProductionPlanDto): Promise<ProductionPlanApiResult<boolean>> => {
  try {
    const response = await http.post('/ProductionPlan/create', data)
    return response.data
  } catch (error: any) {
    console.error('创建生产计划失败:', error)
    throw new Error(error.response?.data?.msg || '创建生产计划失败')
  }
}

// 更新生产计划（为后续功能预留）
export const updateProductionPlan = async (id: number, data: any): Promise<ProductionPlanApiResult<any>> => {
  try {
    const response = await http.put(`/ProductionPlan/${id}`, data)
    return response.data
  } catch (error: any) {
    console.error('更新生产计划失败:', error)
    return {
      msg: '更新失败，请重试',
      code: 500,
      data: null
    }
  }
}

export const uploadFile = async (productionPlanId: number, file: File): Promise<ProductionPlanApiResult<string>> => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('productionPlanId', productionPlanId.toString())
    
    const response = await http.post('/ProductionPlan/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  } catch (error: any) {
    console.error('文件上传失败:', error)
    throw new Error(error.response?.data?.msg || '文件上传失败')
  }
}

// 物品查询API
export const getItemPage = async (query: ItemQueryDto): Promise<ItemPageResult> => {
  try {
    const response = await http.post('/Item/query', query)
    // 直接返回响应数据，因为实际结构中data为null，数据在根级别
    return response.data
  } catch (error: any) {
    console.error('查询物品失败:', error)
    throw new Error(error.response?.data?.msg || '查询物品失败')
  }
}

// 销售订单查询API
export const getSalesOrderPage = async (query: SalesOrderQueryDto): Promise<SalesOrderPageResult> => {
  try {
    const response = await http.post('/SalesOrder/query', query)
    // 直接返回响应数据，因为实际结构中data为null，数据在根级别
    return response.data
  } catch (error: any) {
    console.error('查询销售订单失败:', error)
    throw new Error(error.response?.data?.msg || '查询销售订单失败')
  }
}

// 销售订单物品查询API
export const getSalesOrderItems = async (query: SalesOrderItemQueryDto): Promise<SalesOrderItemPageResult> => {
  try {
    const response = await http.post('/SalesOrder/items', query)
    // 直接返回响应数据，因为实际结构中data为null，数据在根级别
    return response.data
  } catch (error: any) {
    console.error('查询销售订单物品失败:', error)
    throw new Error(error.response?.data?.msg || '查询销售订单物品失败')
  }
}

// 项目相关API
export const getAllProjects = async (params?: {
  ProjectName?: string
  ProjectNumber?: string
  Status?: string
  OnlyActive?: boolean
}): Promise<Project[]> => {
  try {
    const queryParams = new URLSearchParams()
    if (params?.ProjectName) queryParams.append('ProjectName', params.ProjectName)
    if (params?.ProjectNumber) queryParams.append('ProjectNumber', params.ProjectNumber)
    if (params?.Status) queryParams.append('Status', params.Status)
    queryParams.append('OnlyActive', (params?.OnlyActive ?? true).toString())
    
    const response = await http.get(`/Project/all?${queryParams.toString()}`)
    return response.data.data
  } catch (error: any) {
    console.error('获取项目列表失败:', error)
    throw new Error(error.response?.data?.msg || '获取项目列表失败')
  }
}

export default http 